import { Select } from 'antd'
import React from 'react'

// 获取 Select 组件上的props类型
type SelectProps = React.ComponentProps<typeof Select>
//继承 select类型,合并自定义属性
export interface IdSelectProps extends Omit<SelectProps, 'value' | 'onChange' | 'defaultOptionName' | 'options'> {
  value: string | number | null | undefined
  onChange: (value?: number) => void
  defaultOptionName?: string
  options?: { name: string; id: number }[]
}

// type UnionSelectProps = IdSelectProps & Omit<SelectProps, keyof IdSelectProps>

/**
 * value 可以传入多种类型的值
 * onchange只会回调number|undefined类型
 * 当isNaN(Number(value))为true时,代表选择默认类型
 * 当选择默认类型的时候,onChange会回调undefined
 *
 * @param props
 * @returns
 */
export const IdSelect = (props: IdSelectProps) => {
  const { value, onChange, defaultOptionName, options, ...resPorps } = props
  return (
    <Select
      value={options?.length ? toNumber(value) : 0}
      onChange={value => onChange(toNumber(value) || undefined)}
      {...resPorps}
    >
      {defaultOptionName ? <Select.Option value={0}>{defaultOptionName}</Select.Option> : null}
      {options?.map(option => (
        <Select.Option key={option.id} value={option.id}>
          {option.name}
        </Select.Option>
      ))}
    </Select>
  )
}

export const toNumber = (value: IdSelectProps['value'] | unknown) => {
  return isNaN(Number(value)) ? 0 : Number(value)
}
